<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加图片到相册"
    width="70%"
    :close-on-click-modal="false"
  >
    <div class="dialog-content">
      <!-- 图片选择区域 -->
      <div class="image-selection">
        <div class="selection-header">
          <h3>选择图片</h3>
          <el-input
            v-model="searchQuery"
            placeholder="搜索图片"
            class="search-input"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <div v-loading="loading" class="image-grid">
          <el-empty
            v-if="!loading && filteredImages.length === 0"
            description="暂无图片"
          />

          <div
            v-for="image in filteredImages"
            :key="image.id"
            class="image-item"
            :class="{ selected: selectedImages.includes(image.id) }"
            @click="toggleImageSelection(image.id)"
          >
            <el-image
              :src="getFullImageUrl(image.file_path)"
              fit="cover"
              loading="lazy"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>加载失败</span>
                </div>
              </template>
            </el-image>
            <div class="image-info">
              <span class="image-name">{{ image.file_name }}</span>
              <div class="image-tags">
                <el-tag
                  v-for="tag in JSON.parse(image.tags)"
                  :key="tag"
                  size="small"
                  class="tag"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitting"
          :disabled="selectedImages.length === 0"
        >
          添加选中图片
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { Search, Picture } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import axios from "axios";

interface Props {
  visible: boolean;
  albumId: number;
}

const props = defineProps<Props>();
const emit = defineEmits(["update:visible", "added"]);

const dialogVisible = ref(false);
const loading = ref(false);
const submitting = ref(false);
const searchQuery = ref("");
const images = ref<any[]>([]);
const selectedImages = ref<number[]>([]);

// 监听visible属性变化
watch(
  () => props.visible,
  (val) => {
    dialogVisible.value = val;
    if (val) {
      fetchImages();
    } else {
      selectedImages.value = [];
      searchQuery.value = "";
    }
  }
);

// 监听对话框关闭
watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      emit("update:visible", false);
    }
  }
);

// 获取图片列表
const fetchImages = async () => {
  loading.value = true;
  try {
    const response = await axios.get("http://localhost:3000/images", {
      params: { userId: 1 },
    });
    images.value = response.data;
  } catch (error) {
    console.error("获取图片列表失败:", error);
    ElMessage.error("获取图片列表失败");
  } finally {
    loading.value = false;
  }
};

// 过滤图片
const filteredImages = computed(() => {
  if (!searchQuery.value) return images.value;

  const query = searchQuery.value.toLowerCase();
  return images.value.filter((image) => {
    const tags = JSON.parse(image.tags);
    return (
      image.file_name.toLowerCase().includes(query) ||
      tags.some((tag: string) => tag.toLowerCase().includes(query))
    );
  });
});

// 切换图片选择状态
const toggleImageSelection = (imageId: number) => {
  const index = selectedImages.value.indexOf(imageId);
  if (index === -1) {
    selectedImages.value.push(imageId);
  } else {
    selectedImages.value.splice(index, 1);
  }
};

// 获取完整的图片URL
const getFullImageUrl = (path: string) => {
  return `http://localhost:3000/${path}`;
};

// 提交添加图片
const handleSubmit = async () => {
  if (selectedImages.value.length === 0) {
    ElMessage.warning("请选择要添加的图片");
    return;
  }

  submitting.value = true;
  try {
    const response = await axios.post(
      `http://localhost:3000/albums/${props.albumId}/images`,
      {
        imageIds: selectedImages.value,
      }
    );

    ElMessage.success("图片添加成功");
    emit("added");
    dialogVisible.value = false;
  } catch (error) {
    console.error("添加图片失败:", error);
    ElMessage.error("添加图片失败");
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  dialogVisible.value = false;
};
</script>

<style scoped lang="scss">
.dialog-content {
  height: 60vh;
  display: flex;
  flex-direction: column;
}

.image-selection {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow: hidden;
}

.selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;

  h3 {
    margin: 0;
    font-size: 16px;
    color: #303133;
  }

  .search-input {
    width: 240px;
  }
}

.image-grid {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.image-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &.selected {
    border-color: #409eff;
  }

  .el-image {
    width: 100%;
    height: 200px;
  }

  .image-info {
    padding: 8px;
    background: rgba(255, 255, 255, 0.9);
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
  }

  .image-name {
    display: block;
    font-size: 14px;
    color: #303133;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .image-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;

    .tag {
      font-size: 12px;
    }
  }
}

.image-error {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;

  .el-icon {
    font-size: 24px;
    margin-bottom: 8px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
